const Message = require('../../model/message')

exports.send = async (obj,res)=>{
   try {
    var doc = await Message.create({
        ...obj
    })
    var data = {user:doc.send,types:doc.types,message:doc.message,tip:doc._id,time:doc.time}
   } catch (error) {
    return res.send({
      status:400
    })
   }
   res.send({
     status:200,data
   })
}

exports.getmessage = async (uid,fid,pagesize,page,res)=>{
    try {
      var total = await Message.find({$or:[{user:uid,send:fid},{user:fid,send:uid}]}).count()
      var pagecount = Math.ceil(total/pagesize)
      if(page>pagecount){
        return res.send({
          status:201
        })
      }
      var pass =  (page-1)*pagesize
     var doc  = await Message.find({$or:[{user:uid,send:fid},{user:fid,send:uid}]}).populate('send').sort({time:-1}).limit(pagesize).skip(pass)
     var data = []
     var arr = []
    doc.forEach(item=>{
      data.push({
        user:item.send._id,
        tip:item._id,
        img:item.send.avatar,
        types:item.types,
        message:item.message,
        time:item.time
      })
    })
    } catch (error) {
      console.log(error);
      return res.send({
        status:400
      })
    }
    res.send({
      status:200,
      data
    })
}

exports.notreadcount = async (uid,fid,res)=>{
  try {
    var count =  await Message.find({user:uid,send:fid,state:0}).count()
    var doc = await Message.findOne({$or:[{user:uid,send:fid},{user:fid,send:uid}]}).sort({time:-1}).limit(1)
    var news =''
    var time =''
    if(doc){
      if(doc.types ==0){
        news =doc.message
      }
      if(doc.types ==1){
        news ='[图片]'
      }
      if(doc.types ==2){
        news ='[音频]'
      }
      if(doc.types ==3){
        news ='[定位]'
      }
      time = doc.time
    }
  } catch (error) {
    return res.send({
      status:400
    })
  }
  res.send({
    status:200,
    count,
    news,
    time
  })
}

exports.read = async (uid,fid,res)=>{
  try {
    await Message.updateMany({user:uid,send:fid,state:0},{state:1})
  } catch (error) {
    return res.send({
      status:400
    })
  }
  res.send({
    status:200
  })
}